package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 员工管理模块
 */
@RestController
@RequestMapping("employee")
@Api(tags = "员工模块")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    //员工登录
    @PostMapping("/login")
    @ApiOperation("员工登录")
    public R login(@RequestBody Employee employee, HttpSession session) {
        String username = employee.getUsername();
        String password = employee.getPassword();
        Employee one = employeeService.lambdaQuery()
                .eq(Employee::getUsername, username)
                .one();
        if (one == null) {
            return R.error("账户不存在");
        }
        if (!StringUtils.equals(one.getPassword(), DigestUtils.md5DigestAsHex(password.getBytes()))) {
            return R.error("密码错误");
        }
        if (one.getStatus() == 0) {
            return R.error("账户已被禁用！");
        }
        session.setAttribute("employee", one);
        return R.success(one);
    }

    //员工退出
    @PostMapping("logout")
    public R logout(HttpSession session) {
        //销毁session
        session.invalidate();
        return R.success("退出成功");
    }

    //添加员工
    @PostMapping()
    public R add(@RequestBody Employee employee) {
        //设置默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employeeService.save(employee);
        return R.success("添加成功");
    }

    //分页查询
    @GetMapping("page")
    public R selectByPage(int page, int pageSize, String name) {
        //设置分页参数
        Page<Employee> page1 = new Page(page, pageSize);
        employeeService.lambdaQuery()
                .like(StringUtils.isNotBlank(name), Employee::getName, name)
                .orderByDesc(Employee::getUpdateTime)
                .page(page1);
        return R.success(page1);
    }

    //修改状态
    @PutMapping()
    public R update(@RequestBody Employee employee) {
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    //根据id查询
    @GetMapping("{id}")
    public R selectById(@PathVariable long id) {
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }
}




